import store from "../store"
import VueRouter from 'vue-router'

import { findUserByToken } from 'service'

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

const childRoutes = [
  {
    name: 'profile',
    path: '',
    component: () => import('views/profile/home/Home'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'login',
    path: 'login/:returnUrl?',
    component: () => import('views/profile/login/Login'),
    meta: {
      requireAuth: false,
    }
  },
  {
    name: 'profileBlog',
    path: 'blog/manage',
    component: () => import('views/profile/manage/BlogManage'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileBlog',
    path: 'blog/publish',
    component: () => import('views/profile/publish/BlogPublish'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileBlog',
    path: 'blog/edit/:id',
    component: () => import('views/profile/publish/BlogPublish'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileType',
    path: 'type/manage',
    component: () => import('views/profile/manage/TypeManage'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileType',
    path: 'type/publish',
    component: () => import('views/profile/publish/TypePublish'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileType',
    path: 'type/edit/:id',
    component: () => import('views/profile/publish/TypePublish'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileTag',
    path: 'tag/manage',
    component: () => import('views/profile/manage/TagManage'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileTag',
    path: 'tag/publish',
    component: () => import('views/profile/publish/TagPublish'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileTag',
    path: 'tag/edit/:id',
    component: () => import('views/profile/publish/TagPublish'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileCarousel',
    path: 'carousel/manage',
    component: () => import('views/profile/manage/CarouselManage'),
    meta: {
      requireAuth: true
    }
  },
  {
    name: 'profileLink',
    path: 'link/manage',
    component: () => import('views/profile/manage/LinkManage'),
    meta: {
      requireAuth: true
    }
  }
]

const routes = [
  {
    name: 'home',
    path: '/',
    component: () => import('views/home/Home'),
    meta: { title: "Yozora's blog", cover: true }
  },
  {
    name: 'homePage',
    path: '/page/:pageIndex(\\d+)',
    component: () => import('views/home/Home'),
    meta: { title: "Yozora's blog", cover: true }
  },
  {
    name: 'category',
    path: '/category/:id(\\d+)/:page?',
    component: () => import('views/category/Category'),
  },
  {
    name: 'tag',
    path: '/tag/:id(\\d+)/:page?',
    component: () => import('views/tag/Tag'),
  },
  {
    name: 'search',
    path: '/search/:keyword/:page?',
    component: () => import('views/search/Search'),
  },
  {
    name: 'archive',
    path: '/archive/:id(\\d+)/:page?',
    component: () => import('views/archive/Archive'),
  },
  {
    name: 'blog',
    path: '/blog/:id(\\d+)',
    component: () => import('views/blog/Blog'),
  },
  {
    name: 'message',
    path: '/message',
    component: () => import('views/message/Message'),
    meta: { title: '留言' }
  },
  {
    name: 'bangumi',
    path: '/bangumi',
    component: () => import('views/bangumi/Bangumi'),
    meta: { title: '番剧'}
  },
  {
    name: 'link',
    path: '/link',
    component: () => import('views/link/Link'),
    meta: { title: '友链' }
  },
  {
    name: 'about',
    path: '/about',
    component: () => import('views/about/About'),
    meta: { title: '关于' }
  },
  {
    path: '/profile',
    component: () => import('views/profile/Profile'),
    children: childRoutes
  },
  {
    name: 'error',
    path: '/error',
    component: () => import('components/common/NotFound'),
    meta: { title: '404 - 找不到页面', cover: true }
  },
  {
    name: 'NotFound',
    path: '*',
    component: () => import('components/common/NotFound'),
    meta: { title: '404 - 找不到页面', cover: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (localStorage.token) {
      if (store.getters['user/user']) {
        next()
      }
      findUserByToken().then(res => {
        if (res.data.flag) { 
          store.dispatch('user/SETUSER', res.data.data)
          next()
        } else {
          localStorage.removeItem("token")
          next({ name: 'login' })
        }
      }).catch(err => {
        router.push('/error')
      })
    } else {
      next({ 
        name: 'login',
        query: { returnUrl: window.location.href }
      })
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  if(to.meta && to.meta.title) {
    document.title = to.meta.cover ? to.meta.title : to.meta.title + ' - ' + Vue.prototype.documentTitle
  }
})

export default router
